<template>
  <div class="login-container">
    <div class="background-decoration">
      <div class="circle circle-1"></div>
      <div class="circle circle-2"></div>
      <div class="circle circle-3"></div>
      <div class="square square-1"></div>
      <div class="square square-2"></div>
      <div class="dot dot-1"></div>
      <div class="dot dot-2"></div>
      <div class="dot dot-3"></div>
      <div class="dot dot-4"></div>
      <div class="dot dot-5"></div>
    </div>
    <el-card class="login-card">
      <div class="title">
        <h2>后台管理系统</h2>
        <p>{{ isLogin ? '欢迎回来，请登录' : '欢迎加入，请注册' }}</p>
      </div>
      <!-- 登录表单 -->
      <el-form
        v-if="isLogin"
        ref="loginForm"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
      >
        <el-form-item prop="usAccount">
          <el-input
            v-model="loginForm.usAccount"
            placeholder="请输入账号"
            prefix-icon="el-icon-user"
          />
        </el-form-item>
        <el-form-item prop="usPassword">
          <el-input
            v-model="loginForm.usPassword"
            :type="passwordType"
            placeholder="请输入密码"
            prefix-icon="el-icon-lock"
            @keyup.enter.native="handleLogin"
          >
            <i
              slot="suffix"
              :class="passwordType === 'password' ? 'el-icon-view' : 'el-icon-hide'"
              class="show-pwd"
              @click="showPwd"
            />
          </el-input>
        </el-form-item>
        <div class="remember-forgot">
          <el-checkbox v-model="rememberMe">记住密码</el-checkbox>
          <a href="javascript:;">忘记密码？</a>
        </div>
        <el-button
          :loading="loading"
          type="primary"
          class="submit-btn"
          @click.native.prevent="handleLogin"
        >
          {{ loading ? '登录中...' : '登录' }}
        </el-button>
      </el-form>

      <!-- 注册表单 -->
      <el-form
        v-else
        ref="registerForm"
        :model="registerForm"
        :rules="registerRules"
        class="register-form"
      >
        <el-form-item prop="usName">
          <el-input
            v-model="registerForm.usName"
            placeholder="请输入姓名"
            prefix-icon="el-icon-user"
          />
        </el-form-item>
        <el-form-item prop="usAccount">
          <el-input
            v-model="registerForm.usAccount"
            placeholder="请输入账号"
            prefix-icon="el-icon-s-custom"
          />
        </el-form-item>
        <el-form-item prop="usPassword">
          <el-input
            v-model="registerForm.usPassword"
            :type="passwordType"
            placeholder="请输入密码"
            prefix-icon="el-icon-lock"
          >
            <i
              slot="suffix"
              :class="passwordType === 'password' ? 'el-icon-view' : 'el-icon-hide'"
              class="show-pwd"
              @click="showPwd"
            />
          </el-input>
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            :type="passwordType"
            placeholder="请确认密码"
            prefix-icon="el-icon-lock"
          >
            <i
              slot="suffix"
              :class="passwordType === 'password' ? 'el-icon-view' : 'el-icon-hide'"
              class="show-pwd"
              @click="showPwd"
            />
          </el-input>
        </el-form-item>
        <el-form-item prop="usEmail">
          <el-input
            v-model="registerForm.usEmail"
            placeholder="请输入邮箱"
            prefix-icon="el-icon-message"
          />
        </el-form-item>
        <el-button
          :loading="loading"
          type="primary"
          class="submit-btn"
          @click.native.prevent="handleRegister"
        >
          {{ loading ? '注册中...' : '注册' }}
        </el-button>
      </el-form>

      <!-- 切换按钮 -->
      <div class="form-toggle">
        <p>
          {{ isLogin ? '还没有账号？' : '已有账号？' }}
          <a href="javascript:;" @click="toggleForm">
            {{ isLogin ? '立即注册' : '立即登录' }}
          </a>
        </p>
      </div>
    </el-card>
  </div>
</template>

<script>
import { login, register } from '@/api/user'

export default {
  name: 'Login',
  data() {
    // 验证姓名
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入姓名'))
      } else if (value.length < 2 || value.length > 20) {
        callback(new Error('姓名长度在 2 到 20 个字符'))
      } else {
        callback()
      }
    }
    // 验证账号
    const validateAccount = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入账号'))
      } else if (value.length < 4 || value.length > 20) {
        callback(new Error('账号长度在 4 到 20 个字符'))
      } else if (!/^[a-zA-Z0-9_]+$/.test(value)) {
        callback(new Error('账号只能包含字母、数字和下划线'))
      } else {
        callback()
      }
    }
    // 验证密码
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入密码'))
      } else if (value.length < 6 || value.length > 20) {
        callback(new Error('密码长度在 6 到 20 个字符'))
      } else if (!/^[a-zA-Z0-9_]+$/.test(value)) {
        callback(new Error('密码只能包含字母、数字和下划线'))
      } else {
        callback()
      }
    }
    // 验证确认密码
    const validateConfirmPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请确认密码'))
      } else if (value !== this.registerForm.usPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    // 验证邮箱
    const validateEmail = (rule, value, callback) => {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      if (!value) {
        callback(new Error('请输入邮箱'))
      } else if (!emailRegex.test(value)) {
        callback(new Error('请输入正确的邮箱格式'))
      } else {
        callback()
      }
    }

    return {
      isLogin: true,
      loginForm: {
        usAccount: '',
        usPassword: ''
      },
      registerForm: {
        usName: '',
        usAccount: '',
        usPassword: '',
        confirmPassword: '',
        usEmail: ''
      },
      loginRules: {
        usAccount: [{ required: true, trigger: 'blur', validator: validateAccount }],
        usPassword: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      registerRules: {
        usName: [{ required: true, trigger: 'blur', validator: validateUsername }],
        usAccount: [{ required: true, trigger: 'blur', validator: validateAccount }],
        usPassword: [{ required: true, trigger: 'blur', validator: validatePassword }],
        confirmPassword: [{ required: true, trigger: 'blur', validator: validateConfirmPassword }],
        usEmail: [{ required: true, trigger: 'blur', validator: validateEmail }]
      },
      loading: false,
      passwordType: 'password',
      rememberMe: false,
      redirect: undefined
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  created() {
    const rememberedUser = localStorage.getItem('rememberedUser')
    if (rememberedUser) {
      const { usAccount, usPassword } = JSON.parse(rememberedUser)
      this.loginForm.usAccount = usAccount
      this.loginForm.usPassword = usPassword
      this.rememberMe = true
    }
  },
  methods: {
    showPwd() {
      this.passwordType = this.passwordType === 'password' ? '' : 'password'
    },
    // 切换登录/注册表单
    toggleForm() {
      this.isLogin = !this.isLogin
      this.loading = false
      this.$nextTick(() => {
        if (this.isLogin) {
          this.$refs.loginForm?.resetFields()
        } else {
          this.$refs.registerForm?.resetFields()
        }
      })
    },
    // 处理登录
    async handleLogin() {
      this.$refs.loginForm.validate(async valid => {
        if (valid) {
          this.loading = true
          try {
            const res = await this.$store.dispatch('user/login', this.loginForm)
            if(res === true) {
              // 记住密码
              if (this.rememberMe) {
                localStorage.setItem('rememberedUser', JSON.stringify(this.loginForm))
              } else {
                localStorage.removeItem('rememberedUser')
              }
              // 获取用户信息
              await this.$store.dispatch('user/getUserInfo')
              // 生成路由
              await this.$store.dispatch('permission/generateRoutes')
              // 跳转
              this.$router.push({ path: this.redirect || '/' })
              this.$message.success('登录成功')
            } else {
              throw new Error('登录失败')
            }
          } catch (error) {
            console.error('登录失败:', error)
            this.$message.error(error.message || '登录失败')
          } finally {
            this.loading = false
          }
        }
      })
    },
    // 处理注册
    async handleRegister() {
      this.$refs.registerForm.validate(async valid => {
        if (valid) {
          this.loading = true
          try {
            const { confirmPassword, ...registerData } = this.registerForm
            await register(registerData)
            this.$message.success('注册成功，请登录')
            this.isLogin = true
            this.$nextTick(() => {
              this.loginForm.usAccount = this.registerForm.usAccount
              this.$refs.registerForm.resetFields()
            })
          } catch (error) {
            console.error('注册失败:', error)
            this.$message.error(error.message || '注册失败')
          } finally {
            this.loading = false
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  height: 100vh;
  background: linear-gradient(-45deg, #5849A8, #8067D8, #6B5BC0, #7E5FD9);
  background-size: 400% 400%;
  display: flex;
  align-items: center;
  justify-content: center;
  animation: gradientBG 15s ease infinite;
  position: relative;
  overflow: hidden;
}

.background-decoration {
  position: absolute;
  width: 100%;
  height: 100%;
  pointer-events: none;

  .circle {
    position: absolute;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(5px);

    &-1 {
      width: 300px;
      height: 300px;
      top: -100px;
      right: -100px;
      animation: float 8s ease-in-out infinite;
    }

    &-2 {
      width: 200px;
      height: 200px;
      bottom: -50px;
      left: -50px;
      animation: float 10s ease-in-out infinite;
    }

    &-3 {
      width: 150px;
      height: 150px;
      top: 50%;
      right: 15%;
      animation: float 12s ease-in-out infinite;
    }
  }

  .square {
    position: absolute;
    background: rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(5px);
    transform: rotate(45deg);

    &-1 {
      width: 100px;
      height: 100px;
      top: 20%;
      left: 15%;
      animation: rotate 15s linear infinite;
    }

    &-2 {
      width: 70px;
      height: 70px;
      bottom: 20%;
      right: 20%;
      animation: rotate 20s linear infinite reverse;
    }
  }

  .dot {
    position: absolute;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.3);

    &-1 {
      top: 20%;
      left: 30%;
      animation: blink 3s ease-in-out infinite;
    }

    &-2 {
      top: 40%;
      right: 25%;
      animation: blink 4s ease-in-out infinite 1s;
    }

    &-3 {
      bottom: 30%;
      left: 40%;
      animation: blink 5s ease-in-out infinite 0.5s;
    }

    &-4 {
      top: 15%;
      right: 40%;
      animation: blink 4s ease-in-out infinite 2s;
    }

    &-5 {
      bottom: 20%;
      left: 20%;
      animation: blink 3s ease-in-out infinite 1.5s;
    }
  }
}

.login-card {
  width: 400px;
  padding: 20px;
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 8px 32px rgba(88, 73, 168, 0.2);
  transform: translateY(0);
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 15px 35px rgba(88, 73, 168, 0.3);
  }

  .title {
    text-align: center;
    margin-bottom: 30px;
    animation: fadeInDown 0.6s ease;

    h2 {
      font-size: 24px;
      color: #333;
      margin-bottom: 10px;
      position: relative;
      display: inline-block;

      &::after {
        content: '';
        position: absolute;
        bottom: -5px;
        left: 0;
        width: 100%;
        height: 2px;
        background: linear-gradient(90deg, #5849A8, #8067D8);
        transform: scaleX(0);
        transition: transform 0.3s ease;
      }
    }

    &:hover h2::after {
      transform: scaleX(1);
    }

    p {
      font-size: 14px;
      color: #999;
      transition: color 0.3s ease;

      &:hover {
        color: #5849A8;
      }
    }
  }

  .login-form, .register-form {
    :deep(.el-form-item) {
      margin-bottom: 20px;
      animation: fadeInUp 0.6s ease;
      animation-fill-mode: both;

      @for $i from 1 through 5 {
        &:nth-child(#{$i}) {
          animation-delay: #{$i * 0.1}s;
        }
      }
    }

    :deep(.el-input) {
      .el-input__inner {
        height: 40px;
        padding-left: 40px;
        border-radius: 4px;
        transition: all 0.3s ease;
        border: 2px solid transparent;

        &:hover {
          border-color: rgba(88, 73, 168, 0.3);
        }

        &:focus {
          border-color: #5849A8;
          box-shadow: 0 0 0 3px rgba(88, 73, 168, 0.2);
          transform: translateY(-1px);
        }
      }

      .el-input__prefix {
        left: 10px;
        color: #909399;
        transition: all 0.3s ease;
      }

      &:hover .el-input__prefix {
        color: #5849A8;
        transform: scale(1.1);
      }
    }

    .show-pwd {
      color: #909399;
      cursor: pointer;
      margin-right: 8px;
      transition: all 0.3s ease;
      transform-origin: center;

      &:hover {
        color: #5849A8;
        transform: scale(1.2) rotate(180deg);
      }
    }
  }

  .remember-forgot {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    animation: fadeInUp 0.6s ease 0.3s;
    animation-fill-mode: both;

    :deep(.el-checkbox) {
      color: #666;
      transition: all 0.3s ease;

      .el-checkbox__input.is-checked {
        .el-checkbox__inner {
          background-color: #5849A8;
          border-color: #5849A8;
          transform: scale(1.1);
        }

        & + .el-checkbox__label {
          color: #5849A8;
        }
      }

      &:hover {
        transform: translateX(3px);
      }
    }

    a {
      color: #5849A8;
      text-decoration: none;
      font-size: 14px;
      position: relative;
      transition: all 0.3s ease;

      &::after {
        content: '';
        position: absolute;
        bottom: -2px;
        left: 0;
        width: 100%;
        height: 1px;
        background-color: #5849A8;
        transform: scaleX(0);
        transition: transform 0.3s ease;
      }

      &:hover {
        transform: translateX(-3px);
        &::after {
          transform: scaleX(1);
        }
      }
    }
  }

  .submit-btn {
    width: 100%;
    background: linear-gradient(45deg, #5849A8, #8067D8);
    border: none;
    position: relative;
    overflow: hidden;
    transition: all 0.3s ease;
    animation: fadeInUp 0.6s ease 0.4s;
    animation-fill-mode: both;

    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: -100%;
      width: 100%;
      height: 100%;
      background: linear-gradient(
        90deg,
        transparent,
        rgba(255, 255, 255, 0.2),
        transparent
      );
      transition: all 0.5s ease;
    }

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 5px 15px rgba(88, 73, 168, 0.4);
      
      &::before {
        left: 100%;
      }
    }

    &:active {
      transform: translateY(1px);
    }
  }

  .form-toggle {
    text-align: center;
    margin-top: 20px;
    animation: fadeInUp 0.6s ease 0.5s;
    animation-fill-mode: both;

    p {
      color: #666;
      font-size: 14px;

      a {
        color: #5849A8;
        text-decoration: none;
        font-weight: bold;
        transition: all 0.3s ease;

        &:hover {
          color: #8067D8;
          text-decoration: underline;
        }
      }
    }
  }
}

@keyframes gradientBG {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

@keyframes fadeInDown {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes float {
  0%, 100% {
    transform: translateY(0) rotate(0deg);
  }
  50% {
    transform: translateY(-20px) rotate(5deg);
  }
}

@keyframes rotate {
  from {
    transform: rotate(45deg);
  }
  to {
    transform: rotate(405deg);
  }
}

@keyframes blink {
  0%, 100% {
    opacity: 0.3;
    transform: scale(1);
  }
  50% {
    opacity: 0.8;
    transform: scale(1.5);
  }
}
</style> 